fname='D:\RawData\leinmarc\ML_130722_3\S1-T13337';
[vdata,vmeta]=load_vid_data([fname '.vid']);
aux_data=load_lvd([fname '.lvd']);

win=100;

[velP,velM,velP_ind,velM_ind,velP_raw,velM_raw]=get_vel_ind_from_adata(aux_data);
aaa=smooth2(velM,2000);
bbb=smooth2(velP,2000);
rind = [];
rind=bbb<-0.003;

r_onset_frames=[];
shutter_open=find(aux_data(1,:)>2,1,'first');
r_onset_frames=find(diff(rind(vmeta(1,:)+shutter_open))==1);

r_onset_frames(logical([0 diff(r_onset_frames)<200]))=[]

r_onset_frames(r_onset_frames<win)=[];
r_onset_frames(r_onset_frames>size(vdata,3)-win)=[];


figure, plot(bbb(vmeta(1,:)+shutter_open))
hold on
for ind = 1:length(knd)
    plot(r_onset_frames(knd(ind)),0,'.r')
end
set(gca,'xlim',[0 size(vdata,3)])
set(gca,'ylim',[-0.1 0.1])
set(gca,'TickLength',[-0.005 0.025])
box off

r_trig_act=[];
for ind=1:length(knd)
    r_trig_act(:,:,ind)=mean(vdata(:,:,r_onset_frames(knd(ind))+1:r_onset_frames(knd(ind))+win),3)-mean(vdata(:,:,r_onset_frames(knd(ind))-win:r_onset_frames(knd(ind))-1),3);
end

r_trig_act=[];
for ind=1:length(r_onset_frames)
    r_trig_act(:,:,ind)=mean(vdata(:,:,r_onset_frames(ind)+1:r_onset_frames(ind)+win),3)-mean(vdata(:,:,r_onset_frames(ind)-win:r_onset_frames(ind)-1),3);
end

%same norm window
r_trig_act=[];
for ind=1:length(r_onset_frames)
    r_trig_act(:,:,ind)=mean(vdata(:,:,r_onset_frames(ind)+1:r_onset_frames(ind)+win),3)-mean(vdata(:,:,24000:24200),3);
end

for knd = [7 11]
    figure;
    imagesc(r_trig_act(:,:,knd))
    colorbar
    set(gca,'clim',[-1 3])
end

figure, imagesc(mean(r_trig_act,3)./mean(vdata,3))
figure, imagesc(r_trig_act(:,:,11)./mean(vdata,3))


figure, imagesc(r_trig_act(:,:,4)./mean(vdata,3))
figure, imagesc(r_trig_act(:,:,1)-r_trig_act(:,:,2))
figure, imagesc(r_trig_act(:,:,2)-r_trig_act(:,:,1))

figure, plot(bbb(vmeta(1,:)+shutter_open))
hold on
plot(r_onset_frames,0,'.r')
plot(aaa(vmeta(1,:)+shutter_open),'g')

figure;
imagesc(mean(r_trig_act,3))
colorbar
set(gca,'clim',[-1 25])

figure;
imagesc(mean(vdata,3))
colorbar
set(gca,'clim',[-1 200])

rnd_frame=randi([1 size(vdata,3)],1,length(r_onset_frames));

for ind=1:length(rnd_frame)    %length(r_onset_frames)
    r_trig_act(:,:,ind)=mean(vdata(:,:,rnd_frame(1,ind)+1:rnd_frame(1,ind)+50),3)-mean(vdata(:,:,rnd_frame(1,ind)-50:rnd_frame(1,ind)-1),3);
end

figure;
imagesc(mean(r_trig_act,3))
colorbar
set(gca,'clim',[-0.3 0.1])


% check mean fluorescence and running 

exp = [11344 11416 11458 11460 11522 11525 11528 11551 11559 11574]
for xnd = 1:length(exp)
    [mean_fluo(:,xnd)]=check_widefield_illumination(exp(xnd),50);
end

for ynd = 1:length(exp)
    file_name=['D:\tmpData Behavior\widefield M105\S1-T' num2str(exp(ynd)) '.lvd'];
    aux_data=load_lvd(file_name);
    [fract_running(:,ynd)]=check_my_running(aux_data);
    clear('aux_data');
    close;
end

